package com.example.cos;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.http.apache.ApacheHttpClient;

import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;

public class AWSUtil {

    private static final String endpointOverride = "http://172.19.128.7:5246"; // 如果是 MinIO 或其他 S3 兼容服务，请提供正确的端点

    public static void main(String[] args) {
        // 替换为你的访问密钥和秘密密钥
        String accessKey = "ANr9rRGBRULL/2G0etCH";
        String secretKey = "rfcnQJYJ6iWl1UyqVquFcEJXvypi89escfAW7EWR";

        AwsBasicCredentials awsCreds = AwsBasicCredentials.create(accessKey, secretKey);

        ApacheHttpClient.Builder httpClientBuilder = ApacheHttpClient.builder()
                        .maxConnections(100) // 设置最大连接数
                        .connectionTimeout(Duration.ofMillis(10000)) // 设置连接超时，单位毫秒
                        .socketTimeout(Duration.ofMillis(10000))// 设置Socket读取超时，单位毫秒
                        .connectionMaxIdleTime(Duration.ofMillis(10000))// 设置连接最大空闲时间，单位毫秒
                        .connectionTimeToLive(Duration.ofMillis(10000)) // 设置连接存活时间，单位毫秒
                        ;


        S3Client s3 = S3Client.builder()
                .region(Region.US_EAST_1) // 对于非AWS的S3兼容存储，这可以是任意有效的区域
                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                .endpointOverride(URI.create(endpointOverride))
                .httpClientBuilder(ApacheHttpClient.builder())
                .overrideConfiguration(ClientOverrideConfiguration.builder().build())
                .build();
        //downloadFile(s3, "test3", "test.txt", Paths.get("xrb.txt"));

        uploadFile(s3, "test3", "test.docx", "test.docx");
    }

    public static void downloadFile(S3Client s3, String bucketName, String keyName, Path destination) {
        try {
            GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();

            ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(getObjectRequest);
            byte[] data = objectBytes.asByteArray();
            Files.write(destination, data);
            System.out.println("下载文件成功");
        } catch (S3Exception | IOException e) {
            e.printStackTrace();
        }
    }

    public static void uploadFile(S3Client s3, String bucketName, String keyName, String filePath) {
        try {
            PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();
            RequestBody requestBody = RequestBody.fromInputStream(Files.newInputStream(Paths.get(filePath)), Files.size(Paths.get(filePath)));
            PutObjectResponse response = s3.putObject(putOb, RequestBody.fromFile(Paths.get(filePath)));
            System.out.println("上传文件成功：" + response.eTag());
        } catch (S3Exception | IOException e) {
            e.printStackTrace();
        }
    }
}
